package com.zut.chat.service;

import com.zut.chat.entity.ChatMessage;
import com.zut.chat.dto.WebSocketMessage;
import com.zut.chat.mapper.ChatMessageMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static com.zut.chat.entity.table.ChatMessageTableDef.CHAT_MESSAGE;

/**
 * 聊天消息服务类
 */
@Service
public class ChatMessageService extends ServiceImpl<ChatMessageMapper, ChatMessage> {

    /**
     * 保存消息到数据库
     */
    public ChatMessage saveMessage(WebSocketMessage webSocketMessage) {
        ChatMessage chatMessage = ChatMessage.builder()
                .senderNickname(webSocketMessage.getSenderNickname())
                .content(webSocketMessage.getContent())
                .messageType(webSocketMessage.getType().name())
                .sendTime(webSocketMessage.getTimestamp())
                .sessionId(webSocketMessage.getSessionId())
                .imageUrl(webSocketMessage.getImageUrl())
                .videoUrl(webSocketMessage.getVideoUrl())
                .videoTitle(webSocketMessage.getVideoTitle())
                .build();
        
        save(chatMessage);
        return chatMessage;
    }

    /**
     * 获取最近的聊天记录
     */
    public List<ChatMessage> getRecentMessages(int limit) {
        return list(QueryWrapper.create()
                .orderBy(CHAT_MESSAGE.SEND_TIME.desc())
                .limit(limit));
    }

    /**
     * 获取用户的聊天记录
     */
    public List<ChatMessage> getUserMessages(String sessionId, int limit) {
        return list(QueryWrapper.create()
                .where(CHAT_MESSAGE.SESSION_ID.eq(sessionId))
                .orderBy(CHAT_MESSAGE.SEND_TIME.desc())
                .limit(limit));
    }

    /**
     * 获取消息总数
     */
    public long getTotalMessageCount() {
        return count();
    }

    /**
     * 获取后台管理用的消息列表
     */
    public List<ChatMessage> getMessagesForBackend(int page, int size, String senderNickname, String messageType) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        
        if (senderNickname != null && !senderNickname.trim().isEmpty()) {
            queryWrapper.where(CHAT_MESSAGE.SENDER_NICKNAME.like("%" + senderNickname.trim() + "%"));
        }
        
        if (messageType != null && !messageType.trim().isEmpty()) {
            queryWrapper.and(CHAT_MESSAGE.MESSAGE_TYPE.eq(messageType));
        }
        
        return list(queryWrapper
                .orderBy(CHAT_MESSAGE.SEND_TIME.desc())
                .limit(page * size, size));
    }

    /**
     * 获取今日消息统计
     */
    public long getTodayMessageCount() {
        LocalDateTime startOfDay = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        return count(QueryWrapper.create()
                .where(CHAT_MESSAGE.SEND_TIME.ge(startOfDay)));
    }

    /**
     * 清理过期消息（保留最近7天的消息）
     */
    public void cleanExpiredMessages() {
        LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
        remove(QueryWrapper.create()
                .where(CHAT_MESSAGE.SEND_TIME.lt(sevenDaysAgo)));
    }
}
